﻿(function () {
    "use strict";

    function wallItemTemplateSelector(itemPromise) {

        var wallTemplate = document.getElementById("wallTemplate");
        var placeholder = document.createElement("div");

        //Wait for the item
        var renderCompletePromise =
          itemPromise.then(function (item) {

              //wrap the retrieved value for instant access
              return wallTemplate.renderItem(WinJS.Promise.wrap(item))
                  .renderComplete
                  //Extend the rendercomplete promise
                  .then(function (renderedElement) {
                      if (!item.data.likes) {
                          renderedElement.querySelector(".likes").style["display"] = "none";
                      }

                      if (item.data.message && item.data.message.length < 150) {
                          WinJS.Utilities.addClass(renderedElement, "smallMessage");
                      }
                      else {
                          WinJS.Utilities.addClass(renderedElement, "mediumMessage");
                      }

                      placeholder.appendChild(renderedElement);
                  });
          });

        return { element: placeholder, renderComplete: renderCompletePromise };

    }

    function groupInfo() {
        return {
            enableCellSpanning: true,
            cellWidth: 150,
            cellHeight: 50
        };
    }

    WinJS.UI.Pages.define("/pages/home/home.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {

            var that = this;

            this.getPageInformation();
            this.getPageAlbums();
            var login = document.querySelector(".loginButton").winControl;

            if (login.isUserAuthenticated()) {
                this.getPageWall(login.accessToken);
            }
            login.addEventListener("login", function (params) {
                that.getPageWall(login.accessToken);
            });
        },

        getPageInformation: function () {
            var that = this;
            WinJS.xhr({ url: "http://graph.facebook.com/greencurrybsas" }).then(function (response) {
                var d = JSON.parse(response.responseText);
                document.querySelector(".pagetitle").textContent = d.name + " " + d.phone;
                document.querySelector(".about").textContent = d.about;
                document.querySelector(".culinary_team").textContent = "Por " + d.culinary_team;
                document.querySelector(".category").textContent = d.category;
                var pageLink = document.createElement("a");
                pageLink.href = d.link;
                pageLink.textContent = "su página.";
                var pageText = document.createElement("span");
                pageText.textContent = "A " + d.likes + " personas les gusta ";
                document.querySelector(".pageLikes").appendChild(pageText);
                document.querySelector(".pageLikes").appendChild(pageLink);

                document.getElementById("contenthost").style.backgroundImage = "url(" + d.cover.source + ")";

                that.showMap(d.location.latitude, d.location.longitude, d.name, d.location.street + " <br/>t: " + d.phone);

                var website = document.querySelector("a.website");
                website.href = d.website;
                website.text = d.website;
            });

        },
        showMap: function (latitude, longitude, title, description) {
            Microsoft.Maps.loadModule('Microsoft.Maps.Map', { callback: initMap, culture: "en-us", homeRegion: "US" });

            var map;
            var directionsManager;

            function createDirectionsManager() {
                if (!directionsManager) {
                    directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
                }
                directionsManager.resetDirections();
            };

            function createWalkingRoute(from, to) {
                if (!directionsManager) { createDirectionsManager(); }
                directionsManager.resetDirections();
                directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.walking });
                var seattleWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: from });
                directionsManager.addWaypoint(seattleWaypoint);
                var redmondWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: to });
                directionsManager.addWaypoint(redmondWaypoint);
                directionsManager.calculateDirections();
            }

            function showDirections(currentPosition) {
                var currentLocation = new Microsoft.Maps.Location(currentPosition.coords.latitude, currentPosition.coords.longitude);
                var restaurantLocation = new Microsoft.Maps.Location(latitude, longitude);
                if (!directionsManager) {
                    Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createWalkingRoute(currentLocation, restaurantLocation) });
                }
                else {
                    createWalkingRoute(currentLocation, restaurantLocation);
                }
            };

            function initMap() {
                var mapOptions =
                {
                    credentials: "AnByQf4BriO0Rkdr4JkzuUbpd3ZkYqx6gLlN1txZS4_wilBJ4wJqaDFHaXoiiZUE",
                    center: new Microsoft.Maps.Location(latitude, longitude),
                    mapTypeId: Microsoft.Maps.MapTypeId.road, zoom: 16,
                    width: 500, height: 400,
                    showDashboard: false,
                    enableSearchLogo: false,
                };

                navigator.geolocation.getCurrentPosition(showDirections);

                map = new Microsoft.Maps.Map(document.getElementById("bingMap"), mapOptions);
                document.getElementById("bingMap").style.width = "75%";

                var infobox = new Microsoft.Maps.Infobox(map.getCenter(), { title: title, height: 90, width: 180, description: description, showPointer: true });

                infobox.setOptions({ visible: true });
                map.entities.push(infobox);

            }
        },

        getPageAlbums: function () {

            var photos = new WinJS.Binding.List();
            var photosList = document.getElementById("photos").winControl;
            photosList.itemTemplate = document.getElementById("photoTemplate");
            photosList.itemDataSource = photos.dataSource;

            WinJS.xhr({ url: "http://graph.facebook.com/greencurrybsas/albums" }).then(function (response) {
                var d = JSON.parse(response.responseText);
                d.data.forEach(function (album) {
                    // let's fetch each album
                    if (album.cover_photo) {
                        WinJS.xhr({ url: "http://graph.facebook.com/" + album.cover_photo }).then(function (response) {
                            var i = JSON.parse(response.responseText);
                            photos.push({ source: i.images[6].source, height: i.images[6].height, width: i.images[6].width });
                        });
                    }
                });


            });
        },

        getPageWall: function (accessToken) {
            var wall = new WinJS.Binding.List();
            var wallList = document.getElementById("wall").winControl;
            wallList.itemTemplate = wallItemTemplateSelector;
            wallList.itemDataSource = wall.dataSource;
            wallList.layout = new WinJS.UI.GridLayout({ groupInfo: groupInfo });

            WinJS.xhr({ url: "https://graph.facebook.com/greencurrybsas/feed?access_token=" + accessToken }).then(function (response) {
                var f = JSON.parse(response.responseText);
                f.data.forEach(function (message) {
                    message.from.picture = "http://graph.facebook.com/" + message.from.id + "/picture";
                    wall.push(message);
                });
            });

        },

        like: function (element) {
            var login = document.querySelector(".loginButton").winControl;
            var url = "https://graph.facebook.com/" + element.idMessage + "/likes?access_token=" + login.accessToken;
            var that = this;

            WinJS.xhr({ url: url, type: "POST" }).then(function (response) {
                if (response.responseText == "true") {
                    // we don't need to update the whole wall, but still doing so for sample simplicity
                    that.getPageWall(login.accessToken);
                }
            });
        },

        comment: function (element) {
            var flyout = document.querySelector("#commentTextFlyout").winControl;
            flyout.show(element, "top");
            flyout.element.querySelector("button").addEventListener("click", function (sender) { confirmComment(element.idMessage) });
        }
    });

    function confirmComment(idMessage) {
        var commentText = document.querySelector("#commentText").value;

        var login = document.querySelector(".loginButton").winControl;
        var url = "https://graph.facebook.com/" + idMessage + "/comments?access_token=" + login.accessToken;

        WinJS.xhr({ url: url, type: "POST", data: "message=" + commentText }).then(function (response) {
            if (response.responseText.match("id")) {
                // we should update the ui... let's just show a confirmation Message for now...
                var dialog = new Windows.UI.Popups.MessageDialog("Enviamos tu comentario!");
                dialog.showAsync();
            }
        });
    };

})();
